﻿using System;
using Artemis;
using libtcod;
using RL.Components;

namespace RL.Systems
{    
    public abstract class RenderSystem : EntityProcessingSystem
    {
        protected readonly TCODConsole Console;
        protected ComponentMapper<Position> PositionMapper;

        protected RenderSystem(TCODConsole console, params Type[] types) : base(typeof(Position), types)
        {
            Console = console;
        }

        public override void Initialize()
        {
            PositionMapper = new ComponentMapper<Position>(world);
        }
    }

    public class MapRenderSystem : RenderSystem
    {
        private ComponentMapper<GameMap> _gameMapMapper;

        public MapRenderSystem(TCODConsole console) : base(console, typeof(GameMap)) {}

        public override void Initialize()
        {
            _gameMapMapper = new ComponentMapper<GameMap>(world);
            base.Initialize();
        }

        public override void Process(Artemis.Entity e)
        {
            var map = _gameMapMapper.Get(e).MapConsole;
            TCODConsole.blit(map, 0, 0, Console.getWidth(), Console.getHeight(), Console, 1, 1);
        }
    }

    public class SpatialRenderSystem : RenderSystem
    {
        private ComponentMapper<SpatialForm> _spatialFormMapper;

        public SpatialRenderSystem(TCODConsole console) : base(console, typeof(SpatialForm)) {}

        public override void Initialize()
        {
            _spatialFormMapper = new ComponentMapper<SpatialForm>(world);
            base.Initialize();
        }

        public override void Process(Artemis.Entity e)
        {
            var pos = PositionMapper.Get(e);
            var form = _spatialFormMapper.Get(e);
            Console.putCharEx(pos.X, pos.Y, form.Form, form.Color, TCODColor.black);
        }
    }

    public class TextRenderSystem : RenderSystem
    {
        private ComponentMapper<TextForm> _textFormMapper;

        public TextRenderSystem(TCODConsole console) : base(console, typeof(TextForm)) {}

        public override void Initialize()
        {
            _textFormMapper = new ComponentMapper<TextForm>(world);
            base.Initialize();
        }

        public override void Process(Artemis.Entity e)
        {
            var pos = PositionMapper.Get(e);
            var text = _textFormMapper.Get(e).Text;
            Console.print(pos.X, pos.Y, text);
        }
    }
}